var currentCategory = 'cat';
var currentItem = '';

var editImage = document.getElementById("editImage")
var addImage = document.getElementById("addImage")
var file;
function editItemImage(event){
    file = event.target.files[0] || event.dataTransfer.files[0] || this.file.files[0]
}
function doEdit(){
    console.dir(file)
    console.log(file.name)

}

//获取当前操作的商品类型
function setCurrentCategory(categoryId){
    currentCategory  = categoryId;
    showItem(categoryId+'-tab');
}

//获取当前操作的商品
function setCurrentItem(itemId){
    currentItem = itemId;
}

//添加新商品函数
function addNewItemFunc(){
    var itemName = $("#itemName").val();
    var itemStates = $("#itemStates").val();
    var limitNumber = $("#limitNumber").val();
    var numberOfItem = $("#numberOfItem").val();
    var price = $("#priceOfItem").val();
    var limits;
    var description = '/image/' + file.name
    var formData = new FormData()
    formData.append("file",file)
    $("#newItem").modal('hide');

    //转换限购信息：0代表无限制
    if(limitNumber===0)
        limits = "无限制";
    else
        limits = limitNumber;

    //为商品添加id
    var itemId = pinyin.getFullChars(itemName);

    if(itemName===''||itemStates===''||limitNumber===''||numberOfItem===''||price==='')
    {
        $("#failAlertText").text("请完整填写商品信息!");
        showAlert('failAlert');
    }
    else
    {
        //拼接
        var area = "#"+currentCategory+"_cardArea";
        $(area).append("<!--上架商品卡片开始--><div class=\"card border rounded-3 border-success mx-3 my-3\"style=\"width: 13vw; float: left;\" id=\""+itemId+"_card"+"\">"
            +"<!--商品的图片-->"+
            "<img id=\""+ itemId+"_image"+"\" decoding=\"async\" class=\"card-img-top\"style=\"max-width: 13vw; height: 29vh;\"src=\"C:\\Users\\Administrator\\Pictures\\卡牌DIY\\阳光戒裁剪.jpg\">"+
            "<!--商品的信息-->"+
            "<div class=\"card-body\">"+
            "<h5 class=\"card-title\" id=\""+itemId+"\""+">"+itemName+"</h5>"+
            "<p class=\"card-text small lh-1\" id=\""+itemId+"_states"+"\""+">商品状态:"+itemStates+"</p>"+
            "<p class=\"card-text small lh-1\" id=\""+itemId+"_limits"+"\""+">商品限购:"+limits+"</p>"+
            "<p class=\"card-text small lh-1\" id=\""+itemId+"_price"+"\""+">价格:"+price+"</p>"+
            "<p class=\"card-text small lh-1\" id=\""+itemId+"_number"+"\""+">商品库存:"+numberOfItem+"</p><div class=\"row px-2\"><div class=\"col-md-6 text-center\">"+
            "<button type=\"button\" class=\"btn btn-primary\" data-bs-toggle=\"modal\"data-bs-target=\"#editItem\" onclick=\"setCurrentItem('"+itemId+"')"+"\">编辑</button>"+
            "</div>"+
            "<div class=\"col-md-6 text-center\">"+
            "<button type=\"button\" class=\"btn btn-danger\" data-bs-toggle=\"modal\"data-bs-target=\"#takeDownItem\" onclick=\"setCurrentItem('"+itemId+"')"+"\">下架</button>"+
            "</div>"+
            "</div>"+
            "</div>"+
            "</div>"+
            "<!--上架商品卡片结束-->");
        $("#successAlertText").text("上架成功!");
        showAlert('successAlert');
        var add = 'http://localhost:8022/addItem?name=' + encodeURIComponent(itemName) + '&states=' + encodeURIComponent(itemStates) + '&limits=' + encodeURIComponent(limitNumber) + '&quantity=' +
            encodeURIComponent(numberOfItem) + '&description=' + encodeURIComponent(description) + '&unitPrice=' + encodeURIComponent(price) + '&categoryId=' + encodeURIComponent(currentCategory)
        $.ajax
        (
            {
                type:'POST',
                url:add,
                success: function (data)
                {
                    $("#successAlertText").text("上架成功!");
                    showAlert('successAlert');
                },
                error:function (errorMsg)
                {
                    console.log("fail")
                    console.log(errorMsg)
                },
            }
        )
        $.ajax
        (
            {
                type:'POST',
                url:'http://localhost:8022/addImage',
                data: formData,
                processData:false,//数据不做处理
                contentType:false,//不需要设置content-type请求头
                cache:false,//上传文件无需缓存
                success: function (data)
                {
                    //alert("上传图片成功")
                    setCurrentCategory(currentCategory);
                },
                error:function (errorMsg)
                {
                    console.log("fail")
                    console.log(errorMsg)
                },
            }
        )
    }

}

//编辑商品函数
function editItemFunc(){
    var old_name = $("#"+currentItem).text();
    var new_name = $("#editItemName").val();
    var new_state = $("#editItemStates").val();
    var new_limit = $("#editLimitNumber").val();
    var new_number = $("#editNumberOfItem").val();
    var new_price = $("#editPriceOfItem").val();
    var formData = new FormData()
    var new_description = '/image/' + file.name
    formData.append("file",file)
    var limitText;

    $("#editItem").modal('hide');

    if(new_name===''||new_state===''||new_limit===''||new_number===''||new_price===''){
        $("#failAlertText").text("请完整填写商品信息!");
        showAlert('failAlert');
    }
    else{
        if(new_limit===0)
            limitText = "无限制";
        else
            limitText = new_limit;
        var nameDiv = "#"+currentItem;
        var stateDiv = "#"+currentItem+"_states";
        var limitDiv = "#"+currentItem+"_limits";
        var numberDiv = "#"+currentItem+"_number";
        var priceDiv = "#"+currentItem+"_price";
        // $(nameDiv).text(new_name);
        // $(stateDiv).text("商品状态:"+new_state);
        // $(limitDiv).text("商品限购:"+limitText);
        // $(priceDiv).text("价格:"+new_price);
        // $(numberDiv).text("商品库存:"+new_number);
        var change = 'http://localhost:8022/editItem?newName=' + encodeURIComponent(new_name) + '&state=' + encodeURIComponent(new_state) + '&limit=' + encodeURIComponent(new_limit) + '&quantity=' +
            encodeURIComponent(new_number) + '&description=' + encodeURIComponent(new_description)+'&oldName='+encodeURIComponent(old_name) + '&unitPrice=' + encodeURIComponent(new_price)
        //修改图片
        $.ajax
        (
            {
                type: 'POST',
                url: change,
                contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
                success: function (data)
                {
                    $("#successAlertText").text("修改成功!");
                    showAlert('successAlert');
                },
                error:function (errorMsg)
                {
                    console.log("fail")
                    console.log(errorMsg)
                },
            }
        )
        $.ajax
        (
            {
                type:'POST',
                url:'http://localhost:8022/addImage',
                data: formData,
                processData:false,//数据不做处理
                contentType:false,//不需要设置content-type请求头
                cache:false,//上传文件无需缓存
                success: function (data)
                {
                    //alert("上传图片成功")
                    setCurrentCategory(currentCategory);
                },
                error:function (errorMsg)
                {
                    console.log("fail")
                    console.log(errorMsg)
                },
            }
        )


    }
}

//下架所有商品函数
function takeDownAllFunc(){
    $("#"+currentCategory+"_cardArea").empty();
    $("#takeDownAll").modal('hide');
    //ajax修改数据库

    $.ajax({
        url:"http://localhost:8022/deleteCategory?categoryId="+currentCategory,
        type:"POST",
        success:function (data){
            console.log(data);
        }
    });

}

//下架单个商品函数
function takeDownItemFunc(){
    var itemName = $("#"+currentItem).text();
    $("#"+currentItem+"_card").remove();
    $("#takeDownItem").modal('hide');
    //ajax修改数据库

    $.ajax({
        url:"http://localhost:8022/deleteItemByName?itemName="+itemName,
        type: "POST",
        success:function (data){
            console.log(data);
        }
    });

}

//显示信息框
function showAlert(alertId){
    $("#"+alertId).removeClass("invisible");
}

//隐藏信息框
function hideAlert(alertId){
    $("#"+alertId).addClass("invisible");
}

var logout = document.getElementById("btn-logout");

logout.addEventListener('click',onLogoutClick)

function onLogoutClick()
{
    console.log("logout")
    $.ajax(
        {
            type: 'GET',
            url: 'http://localhost:8022/logout',
            success: function (data)
            {
                console.log(data)
                if(data === 'success')
                {
                    window.location='http://localhost:8022/signIn'
                }
                else
                {
                    window.showAlert('注销失败')
                }
            },
            error: function (errorMag)
            {
                window.alert('注销失败')
                console.log(errorMag)
            }
        })
}